package com.wanmait.myhouse.mediatorController;

import com.wanmait.myhouse.dao.*;
import com.wanmait.myhouse.vo.*;
import org.apache.commons.io.FilenameUtils;
import org.apache.taglibs.standard.lang.jstl.test.PageContextImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("mediator")
public class MediatorIconTablerController {
    @PostMapping("update")
    public String update(House house,MultipartFile img,HttpServletRequest request,String out){
        if (!img.isEmpty()){
            String filepath = request.getServletContext().getRealPath("/static/uploadImages");
            String originalFilename = img.getOriginalFilename();
            String fileext = FilenameUtils.getExtension(originalFilename);
            String filename = UUID.randomUUID().toString() + "." + fileext;
            try {
                img.transferTo(new File(filepath+"/"+filename));
                house.setShowImg(filename);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if ("1".equals(out)){
            house.setSold(true);
        }else {
            house.setSold(false);
        }
        HouseDAO houseDAO = new HouseDAO();
        houseDAO.UpDateHouse(house);
        return "redirect:/mediator/showHouse";
    }

    @GetMapping("iconTabler")
    public String iconTabler(Integer id, Model model){
        HouseDAO houseDAO = new HouseDAO();
        House house = houseDAO.FindById(id);
        CityDaO cityDaO = new CityDaO();
        List<City> cityList = cityDaO.FindAll();
        model.addAttribute("cityList",cityList);
        model.addAttribute("house",house);
        TypeDAO typeDAO = new TypeDAO();
        List<Type> typeList = typeDAO.FindAll();
        model.addAttribute("typeList",typeList);
        RoomDAO roomDAO = new RoomDAO();
        List<Room> roomList = roomDAO.FindAll();
        model.addAttribute("roomList",roomList);
        SellMannerDAO sellMannerDAO = new SellMannerDAO();
        List<SellManner> sellMannerList = sellMannerDAO.selectAll();
        model.addAttribute("sellMannerList",sellMannerList);
        return "/mediator/icon_tabler";
    }
}
